#!/bin/bash
#

base_config_file=/data/vm_base.xml
base_disk_file=/data/vm_base_disk.qcow2

# create menu
menu() {
echo "---------------Menu---------------"
echo "1.创建一个虚拟机 "
echo "2.创建多个虚拟机"
echo "3.删除一个虚拟机"
echo "4.删除所有虚拟机"
echo "5.查看虚拟机列表"
echo "6.退出"
echo "----------------------------------"

}
# delete all virtual machine
deleteVm() {
for i in $(virsh list --all | awk '{print $2}'|sed '1,2d'); do
    virsh destroy $i &> /dev/null
    virsh undefine $i &> /dev/null
done
    rm -rf /var/lib/libvirt/images/*
    echo -e "\e[1;32m Delete successfully\e[0m"
}
#delete a virtual machine
delete_A_VM() {
    read -p "please enter VM name: " vm_name
    virsh destroy ${vm_name} &>/dev/null
    virsh undefine ${vm_name} &>/dev/null
    rm -rf /var/lib/libvirt/images/${vm_name}*
    echo -e "\e[1;32m Delete successfully\e[0m"
}
#create a virtual machine
create_A_Vm() {
    read -p "please enter VM name: " vm_name
    disk_name=/var/lib/libvirt/images/${vm_name}.qcow2	
    vm_uuid=$(uuidgen)
    mac_address=52:54:00:$(openssl rand -hex 10 | sed -r 's/(..)(..)(..).*/\1:\2:\3/')
    cp $base_config_file  /etc/libvirt/qemu/${vm_name}.xml    
    qemu-img create -f qcow2 -b $base_disk_file $disk_name &> /dev/null
    # change profile
    sed -ri "s/vm_base/${vm_name}/" /etc/libvirt/qemu/${vm_name}.xml
    sed -ri "/uuid/c \  <uuid>${vm_uuid}</uuid>" /etc/libvirt/qemu/${vm_name}.xml
    sed -ri "/<mac/c \      <mac address='${mac_address}'/>" /etc/libvirt/qemu/${vm_name}.xml
    virsh define /etc/libvirt/qemu/${vm_name}.xml &> /dev/null
    echo -e "\e[1;32m Created successfully \e[0m"
}
# create multiple virtual machine
create_M_Vm() {
read -p "Enter the number of virtual machines: " number

for i in $(seq $number); do

    vm_name=vm${i}_centos79
    disk_name=/var/lib/libvirt/images/${vm_name}.qcow2
    vm_uuid=$(uuidgen)
    mac_address=52:54:00:$(openssl rand -hex 10 | sed -r 's/(..)(..)(..).*/\1:\2:\3/')
    # copy file
    cp $base_config_file  /etc/libvirt/qemu/${vm_name}.xml
    qemu-img create -f qcow2 -b $base_disk_file $disk_name &> /dev/null
    # change file
    sed -ri "s/vm_base/vm${i}_centos79/" /etc/libvirt/qemu/vm${i}_centos79.xml
    sed -ri "/uuid/c \  <uuid>${vm_uuid}</uuid>" /etc/libvirt/qemu/vm${i}_centos79.xml
    sed -ri "/<mac/c \      <mac address='${mac_address}'/>" /etc/libvirt/qemu/vm${i}_centos79.xml

    # build virtual machine
    virsh define /etc/libvirt/qemu/vm${i}_centos79.xml &> /dev/null
    echo -e "\e[1;32m Created successfully \e[0m"
done
}

# main()
menu
while true
do
read -p "please select: " number
case  $number in
    1)
    create_A_Vm	
    ;;
    2)
    create_M_Vm
    ;;
    3)
    delete_A_VM
    ;;
    4)
    deleteVm
    ;;
    5)
    virsh list --all
    ;;
    6)
    echo -e "\e[1;35mThank you for using\e[0m"
    exit
    ;;
    *)
    echo -e "\e[1;31mINPUT ERROR \e[0m"
    ;;
esac
done